package org.wx.datasource;



import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.datasource.unpooled.UnpooledDataSourceFactory;

import javax.sql.DataSource;


/**
 * @author Administrator
 * @date 2022/12/06 14:59
 **/
public class WxDruidDataSourceFactory extends UnpooledDataSourceFactory {

    static DataSource staticDataSource;

    static {
        // JVM关闭时关闭所有连接池 注册钩子方法
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                if(staticDataSource != null){
                    if (staticDataSource instanceof AutoCloseable) {
                        AutoCloseable autoCloseable = (AutoCloseable) staticDataSource;
                        try {
                            autoCloseable.close();
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        });
    }

    public WxDruidDataSourceFactory() {
        this.dataSource = new DruidDataSource();
        staticDataSource = dataSource;
    }
}
